package com.wanli.storemobile.homepage;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.wanli.storemobile.base.BaseFragment;
import com.wanli.storemobile.bean.IdCardBean;
import com.wanli.storemobile.utils.GlideEngine;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wanli.storemobile.R;
import com.wanli.storemobile.base.DataCallBack;
import com.wanli.storemobile.bean.BankCardBean;
import com.wanli.storemobile.bean.ImageBean;
import com.wanli.storemobile.bean.IndustryListBean;
import com.wanli.storemobile.bean.StoreDataBasic;
import com.wanli.storemobile.bean.StoreDataInfo;
import com.wanli.storemobile.bean.StoreDeatilsBean;
import com.wanli.storemobile.bean.UserInfoBean;
import com.wanli.storemobile.dialog.BankDepositDialog;
import com.wanli.storemobile.event.ALiDiscernEvent;
import com.wanli.storemobile.event.ChooseBankEvent;
import com.wanli.storemobile.event.StoreDataEvent;
import com.wanli.storemobile.event.StoreNextEvent;
import com.wanli.storemobile.homepage.model.HomePageModelImpl;
import com.wanli.storemobile.homepage.model.IHomePageModel;
import com.wanli.storemobile.utils.Base64BitmapUtil;
import com.wanli.storemobile.utils.GlideUtils;
import com.wanli.storemobile.utils.PermissionsManager;
import com.wanli.storemobile.utils.SPManager;
import com.wanli.storemobile.utils.SPUtils;
import com.wanli.storemobile.utils.ToastUtil;
import com.wanli.storemobile.widget.ViewLoading;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * 门店信息
 */
public class StoreInfoFragment extends BaseFragment {

    public static final String TITLE_TYPE = "type";
    public static final String MERCHANT_ID = "merchant_id";
    public static final String QUICK_INCOME = "quick_income";
    public static final String CHANNEL_TYPE = "channel_type";
    @BindView(R.id.tv_manage_type)
    TextView tvManageType;
    @BindView(R.id.ll_manage_type)
    LinearLayout llManageType;
    @BindView(R.id.tv_industry)
    TextView tvIndustry;
    @BindView(R.id.ll_industry)
    LinearLayout llIndustry;
    @BindView(R.id.edit_rate)
    EditText editRate;

    @BindView(R.id.tv_account_type)
    TextView tvAccountType;
    @BindView(R.id.ll_acount_type)
    LinearLayout llAcountType;
    @BindView(R.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R.id.ll_bank_name)
    LinearLayout llBankName;
    @BindView(R.id.view_end_time)
    View viewEndTime;
    @BindView(R.id.edit_bank_username)
    EditText editBankUsername;
    @BindView(R.id.edit_bank_mobile)
    EditText editBankMobile;
    @BindView(R.id.edit_bank_num)
    EditText editBankNum;
    @BindView(R.id.tv_into_time)
    TextView tvIntoTime;
    @BindView(R.id.ll_into_time)
    LinearLayout llIntoTime;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.tv_settle_to)
    TextView tvSettleTo;
    @BindView(R.id.ll_settle_to)
    LinearLayout llSettleTo;
    @BindView(R.id.ll_settle_to_layout)
    LinearLayout llSettleToLayout;
    @BindView(R.id.edit_bank_idNumber)
    EditText editBankIdNumber;
    @BindView(R.id.ll_rate_layout)
    LinearLayout llRateLayout;
    @BindView(R.id.iv_no_corporate_id_avatar)
    ImageView iv_no_corporate_id_avatar;
    @BindView(R.id.iv_no_corporate_id_emblem)
    ImageView iv_no_corporate_id_emblem;
    @BindView(R.id.rl_person_id_card)
    RelativeLayout rl_person_id_card;
    @BindView(R.id.rl_bank_card_scan)
    RelativeLayout rl_bank_card_scan;
    @BindView(R.id.iv_bank_card_scan_y)
    ImageView iv_bank_card_scan_y;
    @BindView(R.id.iv_bank_card_scan_n)
    ImageView iv_bank_card_scan_n;
    @BindView(R.id.rl_account_opening_permit)
    RelativeLayout rl_account_opening_permit;
    @BindView(R.id.iv_account_opening_permit)
    ImageView iv_account_opening_permit;
    private String type;
    private ArrayList<String> options1Items = new ArrayList<>();
    private ArrayList<String> options2Items = new ArrayList<>();
    private ArrayList<String> options4Items = new ArrayList<>();
    private ArrayList<String> options5Items = new ArrayList<>();
    private ArrayList<String> options6Items = new ArrayList<>();
    private int dialogType = 1;
    private IHomePageModel homePageModel;
    private List<IndustryListBean.DataBean.ItemListBean> industryList;
    private String industry_id = "";//行业id
    private Gson mGson = new Gson();
    private StoreDeatilsBean.DataBean storeBean;
    private String merchant_id;
    private int quick_income;
    private String channel_type;

    private BottomSheetDialog selectPicDialog;
    private PermissionsManager permissionsManager;
    private String[] permissions;
    private int openType;//0 相册，1相机
    private List<LocalMedia> mediaList = new ArrayList<>();
    private String branchCode = ""; //开户行网点

    private String bankName = "";
    private String bankType = "";

    private String provinceName = "";
    private String cityName = "";
    private String areaName = "";
    private String tBankMobile;
    private String tBankIdNumber;
    private String tBankUsername;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_store_info, container, false);
        ButterKnife.bind(this, view);
        registerEventBus();
        Bundle bundle = getArguments();
        if (bundle != null) {
            type = bundle.getString(TITLE_TYPE);
            StoreDataEvent dataEvent = EventBus.getDefault().getStickyEvent(StoreDataEvent.class);
            if (dataEvent != null) {
                storeBean = dataEvent.getDataBean();
            }
            merchant_id = bundle.getString(MERCHANT_ID);
            quick_income = bundle.getInt(QUICK_INCOME);
            channel_type = bundle.getString(CHANNEL_TYPE);
        }
        initView();
        initData();
        initEvent();
        return view;
    }

    private void initEvent() {

    }


    /**
     * 点击正面
     */
    private void clickFront() {
        idType = 1;
        showPictureSelectorDialog();
    }
    /**
     * 点击背面
     */
    private void clickBack() {
        idType = 2;
        showPictureSelectorDialog();
    }


    private void initView() {

        editRate.setEnabled(false);


        if ("2".equals(channel_type)) {
            editRate.setText("50");
        } else {
            editRate.setText("36");
        }

        permissionsManager = new PermissionsManager(mActivity);


        if (TextUtils.isEmpty(merchant_id)) {
            tvManageType.setText("总店");
//            llSettleToLayout.setVisibility(View.GONE);
            tvSettleTo.setText("");
        } else {
            tvManageType.setText("分店");
//            llSettleToLayout.setVisibility(View.VISIBLE);
            tvSettleTo.setText("结算给当前店");
        }

        if (quick_income == 1) {
            llIntoTime.setVisibility(View.GONE);
            tvIntoTime.setText("T1：隔天到");
        } else {
            llIntoTime.setVisibility(View.VISIBLE);
        }

        options1Items.add("总店");
        options1Items.add("分店");


        options4Items.add("法人结算");
        options4Items.add("非法人结算");
        options4Items.add("对公结算");

        options5Items.add("D0：当天到");
        options5Items.add("D1：第二天到");
        options5Items.add("T1：第二个工作日到");

        options6Items.add("结算给当前店");
        options6Items.add("结算给总店");

    }


    public void initData() {
        homePageModel = new HomePageModelImpl();
//        requestIndustryIndex();

        if (storeBean != null) {
            if (storeBean.getShop_type() == 1) {
                tvManageType.setText("总店");
//                llSettleToLayout.setVisibility(View.GONE);
                tvSettleTo.setText("");
            } else {
                tvManageType.setText("分店");
//                llSettleToLayout.setVisibility(View.VISIBLE);
                if (storeBean.getSettle_to() == 0) {
                    tvSettleTo.setText("结算给当前店");
                } else {
                    tvSettleTo.setText("结算给总店");
                }
            }

            editRate.setText(storeBean.getRate() + "");
            if (!TextUtils.isEmpty(storeBean.getRate() + "")) {
                editRate.setSelection(String.valueOf(storeBean.getRate()).length());
            }


            if (storeBean.getAccount_type() == 1) {
                tvAccountType.setText("公司账户");
            } else {
                tvAccountType.setText("法人账户");
            }


            tvBankName.setText(storeBean.getBranch());

            bankName = storeBean.getBank();
            bankType = storeBean.getBank_type();
            provinceName = storeBean.getProvince();
            cityName = storeBean.getCity();
            areaName = storeBean.getArea();

            branchCode = storeBean.getKdb_bank_code().equals("")? storeBean.getUnionpay(): storeBean.getKdb_bank_code();
            editBankUsername.setText(storeBean.getHolder());
            if (!TextUtils.isEmpty(storeBean.getHolder())) {
                editBankUsername.setSelection(storeBean.getHolder().length());
            }
            editBankMobile.setText(storeBean.getHolder_mobile());
            if (!TextUtils.isEmpty(storeBean.getHolder_mobile())) {
                editBankMobile.setSelection(storeBean.getHolder_mobile().length());
            }
            editBankIdNumber.setText(storeBean.getHolder_id_card_no());
            if (!TextUtils.isEmpty(storeBean.getHolder_id_card_no())) {
                editBankIdNumber.setSelection(storeBean.getHolder_id_card_no().length());
            }
            editBankNum.setText(storeBean.getBank_card_no());
            if (!TextUtils.isEmpty(storeBean.getBank_card_no())) {
                editBankNum.setSelection(storeBean.getBank_card_no().length());
            }

            if (storeBean.getSettlement_cycle() == 0) {
                tvIntoTime.setText("D0：当天到");
            } else if (storeBean.getSettlement_cycle() == 1) {
                tvIntoTime.setText("D1：第二天到");
            } else if (storeBean.getSettlement_cycle() == 2) {
                tvIntoTime.setText("T1：第二个工作日到");
            } else {
                tvIntoTime.setText("");
            }

            int legal_flag = storeBean.getLegal_flag();
            int account_type = storeBean.getAccount_type();


            if (legal_flag == 1 && account_type == 0) {
                tvAccountType.setText("法人结算");
            } else if (legal_flag == 0 && account_type == 0) {
                tvAccountType.setText("非法人结算");
            } else if (legal_flag == 1 && account_type == 1) {
                tvAccountType.setText("对公结算");
            }

            //非法人头像面
            GlideUtils.loadImage(mActivity, iv_no_corporate_id_avatar, storeBean.getNon_leg_idcard_front_pic());
            //非法人国徽面
            GlideUtils.loadImage(mActivity, iv_no_corporate_id_emblem, storeBean.getNon_leg_idcard_back_pic());

            //银行卡正面
            GlideUtils.loadImage(mActivity, iv_bank_card_scan_y, storeBean.getBank_card_front_pic());
            //银行卡反面
            GlideUtils.loadImage(mActivity, iv_bank_card_scan_n, storeBean.getBank_card_back_pic());
            //开户许可证
            GlideUtils.loadImage(mActivity, iv_account_opening_permit, storeBean.getBank_account_permit_pic());
        }


    }

    /**
     * 行业
     */
    public void requestIndustryIndex() {
        homePageModel.requestIndustryIndex(new DataCallBack<IndustryListBean>() {
            @Override
            public void onSuccessful(IndustryListBean bean) {
                industryList = bean.getData().getItemList();
                for (IndustryListBean.DataBean.ItemListBean bean1 : industryList) {
                    options2Items.add(bean1.getName());
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @Subscribe
    public void onChooseBankEvent(ChooseBankEvent event) {

        tvBankName.setText(event.getBankBranch());
        branchCode = event.getBankCode();
        bankName = event.getBank();
    }

    private boolean isViewCreated; // 界面是否已创建完成
    private boolean isVisibleToUser; // 是否对用户可见

    /**
     * Fragment 创建期间setUserVisibleHint()方法是在onActivityCreated()之前被调用
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        tryLoadData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewCreated = true;
        tryLoadData();
    }

    @Subscribe
    public void onALiDiscernEvent(ALiDiscernEvent event) {
        //身份证 正面
        if (123 == event.getType()) {

            if (!"非法人结算".equals( tvAccountType.getText().toString().trim())) {
                tBankMobile = event.getImgPath();
                editBankMobile.setText(tBankMobile);
            }

        }
        if (456 == event.getType()) {

            tBankUsername = event.getImgPath();
            editBankUsername.setText(tBankUsername);
        }
        if (789 == event.getType()) {
            tBankIdNumber = event.getImgPath();
            editBankIdNumber.setText(tBankIdNumber);

        }

    }

    public void tryLoadData() {
        if (isViewCreated && isVisibleToUser) {
            String name = editBankUsername.getText().toString();
            String mobile = editBankMobile.getText().toString();
            String idNumber = editBankIdNumber.getText().toString();
            StoreDataBasic storeDataBasic = null;
            if (!TextUtils.isEmpty(SPManager.getInstance().getStoreBasic())) {
                storeDataBasic = mGson.fromJson(SPManager.getInstance().getStoreBasic(), StoreDataBasic.class);
            }
//            if (TextUtils.isEmpty(name) && storeDataBasic != null) {
//                if (!TextUtils.isEmpty(storeDataBasic.getLegal_name())) {
//                    editBankUsername.setText(storeDataBasic.getLegal_name());
//                }
//            }
//            if (TextUtils.isEmpty(mobile) && storeDataBasic != null) {
//                if (!TextUtils.isEmpty(storeDataBasic.getContact_mobile())) {
//                    editBankMobile.setText(storeDataBasic.getContact_mobile());
//                }
//            }
//            if (TextUtils.isEmpty(idNumber) && storeDataBasic != null) {
//                if (!TextUtils.isEmpty(storeDataBasic.getLegal_id_card_no())) {
//                    editBankIdNumber.setText(storeDataBasic.getLegal_id_card_no());
//                }
//            }
        }
        if (isViewCreated && !isVisibleToUser) {
            Log.d("---", "333333333333333333333333");
            StoreDataInfo dataInfo = new StoreDataInfo();
            String shop_type = tvManageType.getText().toString();
            if ("总店".equals(shop_type)) {
                dataInfo.setShop_type("1");
            } else if ("分店".equals(shop_type)) {
                dataInfo.setShop_type("0");
            } else {
                dataInfo.setShop_type("");
            }

            String settle_to = tvSettleTo.getText().toString();

//            if ("结算给当前店".equals(settle_to)) {
//                dataInfo.setSettle_to("0");
//            } else if ("结算给总店".equals(settle_to)) {
//                dataInfo.setSettle_to("1");
//            } else {
//                dataInfo.setSettle_to("0");
//            }

            dataInfo.setIndustry_id(industry_id);
            dataInfo.setRate(editRate.getText().toString());






            String account_type = tvAccountType.getText().toString();

            if ("法人账户".equals(account_type)) {
                dataInfo.setAccount_type("0");
            } else if ("公司账户".equals(account_type)) {
                dataInfo.setAccount_type("1");
            } else {
                dataInfo.setAccount_type("");
            }


            dataInfo.setBranch_province(provinceName);
            dataInfo.setBranch_city(cityName);
            dataInfo.setOpen_acc_area(areaName);

            dataInfo.setBank(bankName);
            dataInfo.setBank_type(bankType);
            dataInfo.setBranch(tvBankName.getText().toString());
            dataInfo.setBranchCode(branchCode);
            dataInfo.setUnionpay(branchCode);

            dataInfo.setHolder(editBankUsername.getText().toString());
            dataInfo.setHolder_mobile(editBankMobile.getText().toString());
            dataInfo.setHolder_id_card_no(editBankIdNumber.getText().toString());
            dataInfo.setBank_card_no(editBankNum.getText().toString());

            String settlement_cycle = tvIntoTime.getText().toString();
            if ("D0：当天到".equals(settlement_cycle)) {
                dataInfo.setSettlement_cycle("0");
            } else if ("D1：第二天到".equals(settlement_cycle)) {
                dataInfo.setSettlement_cycle("1");
            } else if ("T1：第二个工作日到".equals(settlement_cycle)) {
                dataInfo.setSettlement_cycle("2");
            } else {
                dataInfo.setSettlement_cycle("0");
            }
            String accountType = tvAccountType.getText().toString().trim();

            if ("法人结算".equals(accountType)) {
                dataInfo.setLegal_flag("1");
                dataInfo.setAccount_type("0");
                rl_person_id_card.setVisibility(View.GONE);
                rl_bank_card_scan.setVisibility(View.VISIBLE);
                rl_account_opening_permit.setVisibility(View.GONE);
            } else if ("非法人结算".equals(accountType)) {
                dataInfo.setLegal_flag("0");
                dataInfo.setAccount_type("0");
                rl_person_id_card.setVisibility(View.VISIBLE);
                rl_bank_card_scan.setVisibility(View.VISIBLE);
                rl_account_opening_permit.setVisibility(View.GONE);
            } else if ("对公结算".equals(accountType)) {
                dataInfo.setLegal_flag("1");
                dataInfo.setAccount_type("1");
                rl_person_id_card.setVisibility(View.GONE);
                rl_bank_card_scan.setVisibility(View.GONE);
                rl_account_opening_permit.setVisibility(View.VISIBLE);
            }

            String legal_flag = dataInfo.getLegal_flag();

            if ("0".equals(legal_flag)) {
                dataInfo.setUnincorporated_name(editBankUsername.getText().toString().trim());
                dataInfo.setUnincorporated_id(editBankIdNumber.getText().toString().trim());
            }

            Log.e("哒哒哒=结算类型", dataInfo.getLegal_flag());
            Log.e("哒哒哒=账户类型", dataInfo.getAccount_type());
            Log.e("哒哒哒=非法人姓名", dataInfo.getUnincorporated_name());
            Log.e("哒哒哒=非法人身份证", dataInfo.getUnincorporated_id());
            SPManager.getInstance().saveStoreInfo(mGson.toJson(dataInfo));
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    private void showPickerView() {
        // 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                if (dialogType == 1) {
                    tvManageType.setText(options1Items.get(options1));
                    if (options1 == 1) {
//                        llSettleToLayout.setVisibility(View.VISIBLE);
                    } else {
//                        llSettleToLayout.setVisibility(View.GONE);
                        tvSettleTo.setText("");
                    }
                } else if (dialogType == 2) {
                    if (industryList != null && industryList.size() > 0) {
                        industry_id = industryList.get(options1).getId() + "";
                        tvIndustry.setText(options2Items.get(options1));
                    }
                } else if (dialogType == 4) {
                    if ("法人结算".equals(options4Items.get(options1))) {
                        rl_person_id_card.setVisibility(View.GONE);
                        rl_bank_card_scan.setVisibility(View.VISIBLE);
                        rl_account_opening_permit.setVisibility(View.GONE);


                        String trim = tvAccountType.getText().toString().trim();

                        if ("非法人结算".equals(trim)){
                            editBankUsername.setText("");
                            editBankIdNumber.setText("");
                            editBankMobile.setText("");
                            editBankNum.setText("");

                            EventBus.getDefault().post(new ALiDiscernEvent(11, ""));
                            EventBus.getDefault().post(new ALiDiscernEvent(12,""));
                            EventBus.getDefault().post(new ALiDiscernEvent(4, ""));
                            EventBus.getDefault().post(new ALiDiscernEvent(9, ""));



                            iv_no_corporate_id_avatar.setImageResource(R.drawable.iv_camera);
                            iv_no_corporate_id_emblem.setImageResource(R.drawable.iv_camera);
                            iv_bank_card_scan_y.setImageResource(R.drawable.iv_camera);
                            iv_bank_card_scan_n.setImageResource(R.drawable.iv_camera);


                        }




                    } else if ("非法人结算".equals(options4Items.get(options1))) {
                        rl_person_id_card.setVisibility(View.VISIBLE);
                        rl_bank_card_scan.setVisibility(View.VISIBLE);
                        rl_account_opening_permit.setVisibility(View.GONE);

                        String trim = tvAccountType.getText().toString().trim();

                        if ("法人结算".equals(trim)||"对公结算".equals(trim)){
                            editBankUsername.setText("");
                            editBankIdNumber.setText("");
                            editBankMobile.setText("");
                            editBankNum.setText("");

                            EventBus.getDefault().post(new ALiDiscernEvent(11, ""));
                            EventBus.getDefault().post(new ALiDiscernEvent(12,""));
                            EventBus.getDefault().post(new ALiDiscernEvent(4, ""));
                            EventBus.getDefault().post(new ALiDiscernEvent(9, ""));

                            iv_no_corporate_id_avatar.setImageResource(R.drawable.iv_camera);
                            iv_no_corporate_id_emblem.setImageResource(R.drawable.iv_camera);
                            iv_bank_card_scan_y.setImageResource(R.drawable.iv_camera);
                            iv_bank_card_scan_n.setImageResource(R.drawable.iv_camera);



                        }




                    } else if ("对公结算".equals(options4Items.get(options1))) {
                        rl_person_id_card.setVisibility(View.GONE);
                        rl_bank_card_scan.setVisibility(View.GONE);
                        rl_account_opening_permit.setVisibility(View.VISIBLE);


                        String trim = tvAccountType.getText().toString().trim();

                        if ("非法人结算".equals(trim)){
                            editBankUsername.setText("");
                            editBankIdNumber.setText("");
                            editBankMobile.setText("");
                            editBankNum.setText("");

                            EventBus.getDefault().post(new ALiDiscernEvent(11, ""));
                            EventBus.getDefault().post(new ALiDiscernEvent(12,""));
                            EventBus.getDefault().post(new ALiDiscernEvent(4, ""));
                            EventBus.getDefault().post(new ALiDiscernEvent(9, ""));

                            iv_no_corporate_id_avatar.setImageResource(R.drawable.iv_camera);
                            iv_no_corporate_id_emblem.setImageResource(R.drawable.iv_camera);
                            iv_bank_card_scan_y.setImageResource(R.drawable.iv_camera);
                            iv_bank_card_scan_n.setImageResource(R.drawable.iv_camera);

                        }
                    }

                    tvAccountType.setText(options4Items.get(options1));



                } else if (dialogType == 5) {
                    tvIntoTime.setText(options5Items.get(options1));
                } else if (dialogType == 6) {
                    tvSettleTo.setText(options6Items.get(options1));
                }
            }
        }).setTitleText("")
                .setTitleSize(16)
                .setSubmitColor(getResources().getColor(R.color.text_color_2))//确定按钮文字颜色
                .setSubCalSize(14)
                .setCancelColor(getResources().getColor(R.color.text_color_2))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.white))
                .setDividerColor(getResources().getColor(R.color.line_color_gray))
                .setTextColorCenter(getResources().getColor(R.color.text_color_2))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2)
                .isDialog(true)
                .build();



        if (dialogType == 1) {
            pvOptions.setPicker(options1Items);
        } else if (dialogType == 2) {
            pvOptions.setPicker(options2Items);
        } else if (dialogType == 4) {
            pvOptions.setPicker(options4Items);
        } else if (dialogType == 5) {
            pvOptions.setPicker(options5Items);
        } else if (dialogType == 6) {
            pvOptions.setPicker(options6Items);
        }




        Dialog mDialog = pvOptions.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvOptions.getDialogContainerLayout().setLayoutParams(params);

            Window window = mDialog.getWindow();
            if (window != null) {
                window.setWindowAnimations(R.style.picker_view_slide_anim);//修改动画样式
                window.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                lp.gravity = Gravity.BOTTOM;
            }
        }
        pvOptions.show();

    }
    int idType;
    @OnClick({R.id.iv_bank_card_scan_y, R.id.iv_bank_card_scan_n,R.id.ll_manage_type, R.id.ll_industry, R.id.ll_settle_to, R.id.ll_acount_type, R.id.ll_bank_name, R.id.ll_into_time, R.id.tv_commit, R.id.iv_no_corporate_id_avatar, R.id.iv_no_corporate_id_emblem, R.id.iv_account_opening_permit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_bank_card_scan_y:
                idType = 3;
                showPictureSelectorDialog();
                break;
            case R.id.iv_bank_card_scan_n:
                idType = 4;
                showPictureSelectorDialog();
                break;
            case R.id.ll_manage_type:
//                dialogType = 1;
//                showPickerView();
                break;
            case R.id.ll_industry:
                dialogType = 2;
                showPickerView();
                break;

            case R.id.ll_acount_type:

                dialogType = 4;
                showPickerView();
                break;
            case R.id.ll_bank_name:

                BankDepositDialog dialog = BankDepositDialog.newInstance("0");

                dialog.show(getChildFragmentManager(), "dialog");

                dialog.setOnCallBackListener((branch_province, branch_city, open_acc_area, bank_name, bank_type, open_acc_bank_name, open_acc_bank_type) -> {


                    provinceName = branch_province;
                    cityName = branch_city;
                    areaName = open_acc_area;

                    bankName = bank_name;
                    bankType = bank_type;

                    if (TextUtils.isEmpty(open_acc_area)) {
                        areaName = cityName;
                    }


                    tvBankName.setText(open_acc_bank_name);
                    branchCode = open_acc_bank_type;


                    Log.e("-----branch_province", branch_province);
                    Log.e("-----branch_city", branch_city);
                    Log.e("-----open_acc_area", open_acc_area);
                    Log.e("-----bank_name", bank_name);
                    Log.e("-----bank_type", bank_type);
                    Log.e("-----open_acc_bank_name", open_acc_bank_name);
                    Log.e("-----open_acc_bank_type", open_acc_bank_type);

                });

                break;
            case R.id.ll_into_time:

                if ("1".equals(channel_type)){
                    dialogType = 5;
                    showPickerView();
                }
                
                break;
            case R.id.ll_settle_to:
                dialogType = 6;
                showPickerView();
                break;
            case R.id.tv_commit:
                EventBus.getDefault().post(new StoreNextEvent(3));
                break;
            case R.id.iv_no_corporate_id_avatar:
                //非法人身份证头像面（原件）
                idType = 1;
                clickFront();
                break;
            case R.id.iv_no_corporate_id_emblem:
                //非法人身份证国徽面（原件）
                idType = 2;
                clickBack();
                break;
            case R.id.iv_account_opening_permit:
                //开户许可证（原件）
                idType = 5;
                showPictureSelectorDialog();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> mediaList = PictureSelector.obtainMultipleResult(data);
                    if (mediaList.size() > 0) {
                        String imgPath = mediaList.get(0).getCompressPath();
                        requestUploadFile(imgPath);
                    }
                    break;
            }
        }

    }

    /**
     * 上传图片
     */
    public void requestUploadFile(String imgPath) {
        ViewLoading.showProgress(mActivity, "上传中......");
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        String file = Base64BitmapUtil.bitmapToBase64(bitmap);
        homePageModel.requestUploadFile("store", file, new DataCallBack<ImageBean>() {
            @Override
            public void onSuccessful(ImageBean bean) {
                if (isDestroy()) {
                    return;
                }
                ToastUtil.showShort("上传成功");


                //1 身份证头像面 2 身份证国徽面 3 银行卡
                if (1 == idType) {
                    EventBus.getDefault().post(new ALiDiscernEvent(11, bean.getData()));
                    requestAliIdCard(bean.getData(), "face");
                    GlideUtils.loadImage(mActivity, iv_no_corporate_id_avatar, bean.getData());
                } else if (2 == idType) {
                    EventBus.getDefault().post(new ALiDiscernEvent(12, bean.getData()));
                    requestAliIdCard(bean.getData(), "back");
                    GlideUtils.loadImage(mActivity, iv_no_corporate_id_emblem, bean.getData());

                } else if (3 == idType) {
                    EventBus.getDefault().post(new ALiDiscernEvent(4, bean.getData()));
                    requestAliBankCard(bean.getData());
                    GlideUtils.loadImage(mActivity, iv_bank_card_scan_y, bean.getData());
                } else if (4 == idType) {
                    EventBus.getDefault().post(new ALiDiscernEvent(9, bean.getData()));
                    requestAliBankCard(bean.getData());
                    GlideUtils.loadImage(mActivity, iv_bank_card_scan_n, bean.getData());
                }else if (5 == idType) {
                    EventBus.getDefault().post(new ALiDiscernEvent(10, bean.getData()));
//                    requestAccountOpeningPermit(bean.getData());
                    GlideUtils.loadImage(mActivity, iv_account_opening_permit, bean.getData());
                }


            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestAliIdCard(String imgPath, String side) {
        ViewLoading.showProgress(mActivity, "识别中......");

        homePageModel.requestAliIdCard(imgPath, side, new DataCallBack<IdCardBean>() {
            @Override
            public void onSuccessful(IdCardBean bean) {
                if (bean.getData() != null && bean.getData().isSuccess()) {
                    ToastUtil.showShort("识别成功");
                    if ("face".equals(side)) {
                        editBankIdNumber.setText(bean.getData().getNum());
                        editBankUsername.setText(bean.getData().getName());

                    }

                } else {
                    ToastUtil.showShort("识别失败，请输入");
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });

    }

    public void requestAliBankCard(String imgPath) {
        homePageModel.requestAliBankCard(imgPath, new DataCallBack<BankCardBean>() {
            @Override
            public void onSuccessful(BankCardBean bean) {
                if (bean.getData() != null && bean.getData().isSuccess()) {
                    ToastUtil.showShort("识别成功");
                    editBankNum.setText(bean.getData().getCard_num());
                    if (!TextUtils.isEmpty(bean.getData().getCard_num())) {
                        editBankNum.setSelection(bean.getData().getCard_num().length());
                    }

                } else {
                    ToastUtil.showShort("识别失败，请输入");
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private void showPictureSelectorDialog() {

        selectPicDialog = new BottomSheetDialog(mActivity, R.style.Dialog);
        selectPicDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_bottom_select_pictrue, null);
        // 相册
        TextView album = view.findViewById(R.id.tv_select_pictrue_album);
        // 相机
        TextView camera = view.findViewById(R.id.tv_select_pictrue_camera);
        // 取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);

        album.setOnClickListener(v -> handlerPhotoAlbumClick());
        camera.setOnClickListener(v -> handlerCameraClick());
        cancel.setOnClickListener(v -> cancelPictureDialog());

        selectPicDialog.setContentView(view);
        selectPicDialog.show();
    }

    /**
     * 点击相机
     */
    private void handlerCameraClick() {
        openType = 1;
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.CAMERA};

        if (PermissionsManager.checkPermissions(permissions)) {
            openCamera();
            cancelPictureDialog();
            return;
        }

        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openCamera();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 点击相册
     */
    private void handlerPhotoAlbumClick() {
        openType = 0;
        cancelPictureDialog();
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.READ_EXTERNAL_STORAGE};

        if (PermissionsManager.checkPermissions(permissions)) {
            openPhotoAlbum();
            cancelPictureDialog();
            return;
        }
        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        PictureSelector.create(StoreInfoFragment.this)
                .openCamera(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
        cancelPictureDialog();

    }

    /**
     * 打开相册
     */
    private void openPhotoAlbum() {
        PictureSelector.create(StoreInfoFragment.this)//
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于20kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void cancelPictureDialog() {
        if (selectPicDialog != null) {
            selectPicDialog.cancel();
        }
    }

    @Override
    public void handlerPermissionForActivityResult() {
        if (PermissionsManager.checkPermissions(permissions)) {
            if (openType == 0) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else if (openType == 1) {
                openCamera();
                cancelPictureDialog();
            }
        }
    }
}